import java.util.LinkedList;
import java.util.Queue;

//地图分析
//测试链接：https://leetcode.cn/problems/as-far-from-land-as-possible/description/
public class MaxDistance {
    int[] dx = { -1, 1, 0, 0 };
    int[] dy = { 0, 0, -1, 1 };
    int m, n;

    public int maxDistance1(int[][] grid) {
        m = grid.length; n = grid[0].length;
        boolean[][] vis = new boolean[m][n];

        Queue<int[]> q = new LinkedList<>();
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(grid[i][j] == 1) {  //从大陆出发，多源BFS找到离大陆最远的位置
                    q.add(new int[]{i,j});
                    vis[i][j] = true;
                }
            }
        }
        int dis = -1;
        while(!q.isEmpty()) {
            dis++;
            int size = q.size();
            while(size-- != 0) {
                int[] t = q.poll();
                int a = t[0], b = t[1];
                for(int i = 0; i < 4; i++) {
                    int x = a + dx[i], y = b + dy[i];
                    if(x >= 0 && x < m && y >= 0 && y < n && !vis[x][y]) {
                        vis[x][y] = true;
                        q.add(new int[] {x,y});
                    }
                }
            }
        }
        return dis == 0 ? -1 : dis;
    }

    public int maxDistance2(int[][] grid) {
        m = grid.length;
        n = grid[0].length;
        int[][] dist = new int[m][n];

        Queue<int[]> q = new LinkedList<>();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                dist[i][j] = -1; //初始化为-1

                if (grid[i][j] == 1) { //从大陆出发，多源BFS找到离大陆最远的位置
                    q.add(new int[] { i, j });
                    dist[i][j] = 0;
                }
            }
        }
        int ans = -1;
        while (!q.isEmpty()) {
            int[] t = q.poll();
            int a = t[0], b = t[1];
            for (int i = 0; i < 4; i++) {
                int x = a + dx[i], y = b + dy[i];
                if (x >= 0 && x < m && y >= 0 && y < n && dist[x][y] == -1) {
                    dist[x][y] = dist[a][b] + 1;
                    q.add(new int[] { x, y });
                    ans = Math.max(ans, dist[x][y]);
                }
            }

        }
        return ans;
    }
}
